package com.zzzzzz.common.util;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

public class FileUtils {
	
	public static byte[] scaleImage(byte[] originalBytes, String extension, int scaledMaxWidth, int scaledMaxHeight) throws IOException {
		BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(originalBytes));
		int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_RGB : originalImage.getType();
		
		int originalWidth = originalImage.getWidth();
		int originalHeight = originalImage.getHeight();
		if (originalWidth <= scaledMaxWidth && originalHeight <= scaledMaxHeight) {
			return originalBytes;
		}
		
		float scaledWidth = 0;
		float scaledHeight = 0;
		float ratio = (float)originalWidth / (float)originalHeight;

		if(ratio > 1){
			scaledWidth = scaledMaxWidth;
			scaledHeight = scaledMaxWidth / ratio;

			if(scaledHeight > scaledMaxHeight){
				scaledWidth = scaledMaxHeight * ratio;
				scaledHeight = scaledWidth / ratio;
			}
		}else{
			scaledWidth = scaledMaxHeight * ratio;
			scaledHeight = scaledMaxHeight;

			if(scaledWidth > scaledMaxWidth){
				scaledHeight = scaledMaxWidth / ratio;
				scaledWidth = scaledHeight * ratio;
			}
		}
		
		byte[] scaledImage = getScaledImage(originalImage, extension, type, (int)scaledWidth, (int)scaledHeight);
		return scaledImage;
	}
	
	private static byte[] getScaledImage(BufferedImage originalImage, String extension, int type, int scaledWidth, int scaledHeight) throws IOException {
		BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight , type);
		Graphics2D g = scaledImage.createGraphics();
		g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
		g.dispose();
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		ImageIO.write(scaledImage, extension, byteStream);
		return byteStream.toByteArray();
	}
	
}
